<template>
  <div>
    <!-- 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>库存管理</el-breadcrumb-item>
      <el-breadcrumb-item>入库/出库记录</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索区域 -->
    <el-card>
      <el-row :gutter="25">
      <el-col :span="10">
        <el-input 
          placeholder="请输入商品名称或仓库地址" 
          v-model="queryInfo.query" 
          clearable
          @clear="getInventoryRecords"
        >
          <template #append>
            <el-button 
              icon="el-icon-search" 
              @click="getInventoryRecords"
            ></el-button>
          </template>
        </el-input>
      </el-col>

      <el-col :span="6">
        <el-select v-model="selectedVarietyType" placeholder="请选择种类" @change="getInventoryRecords">
          <el-option label="无" value=""></el-option>
          <el-option
            v-for="type in varietyTypes"
            :key="type"
            :label="type"
            :value="type">
          </el-option>
        </el-select>
      </el-col>

      <el-col :span="6">
        <el-select v-model="selectedLocation" placeholder="请选择仓库地址" @change="getInventoryRecords">
          <el-option
            v-for="location in warehouseLocations"
            :key="location"
            :label="location"
            :value="location">
          </el-option>
        </el-select>
      </el-col>

      <el-col :span="4">
        <el-button type="primary" icon="el-icon-refresh" @click="refreshData">
          刷新
        </el-button>
      </el-col>
    </el-row>
    
      <el-table :data="inventoryRecords" border stripe>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="时间" prop="timestamp" sortable></el-table-column>
        <el-table-column label="商品名称" prop="productName"></el-table-column>
        <el-table-column label="数量(吨)" prop="quantity"></el-table-column>
        <el-table-column label="操作类型" prop="type">
          <template v-slot:default="scope">
            <span :style="{ color: scope.row.type === 'in' ? 'green' : 'red' }">
              {{ scope.row.type === 'in' ? '入库' : '出库' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="仓库地址" prop="location"></el-table-column>
        <el-table-column label="操作人" prop="employeeUsername"></el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div style="margin-top: 20px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      queryInfo: {
        query: '', // 搜索关键字
        pageNum: 1, // 当前页码
        pageSize: 10 // 每页显示数量
      },
      inventoryRecords: [], // 表格数据
      total: 0, // 总条数
      varietyTypes: [], // 所有种类
      selectedVarietyType: '', // 选中的种类
      warehouseLocations: [], // 所有仓库地址
      selectedLocation: '' // 选中的仓库地址
    };
  },
  created() {
    this.getWarehouseLocations();
    this.fetchVarietyTypes();     // 获取种类
    this.getInventoryRecords();
  },
  methods: {
    async getInventoryRecords() {
      try {
        const params = {
          pageNum: this.queryInfo.pageNum,
          pageSize: this.queryInfo.pageSize,
          varietyType: this.selectedVarietyType || '',
          location: this.selectedLocation || ''
        };

        const response = await axios.get('/inventory/records', { params });

        // 修改这里 👇 使用 list 而不是 data
        this.inventoryRecords = response.data.list || [];
        this.total = response.data.total;
      } catch (error) {
        console.error('获取入库/出库记录失败:', error);
        this.$message.error('获取数据失败，请稍后再试');
      }
    },
    async refreshData() {
      try {
        await this.getInventoryRecords();
        this.$message.success('数据已刷新');
      } catch (error) {
        console.error('刷新数据失败:', error);
        this.$message.error('刷新失败，请稍后再试');
      }
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getInventoryRecords();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getInventoryRecords();
    },
    async fetchVarietyTypes() {
      try {
        const response = await axios.get('/agricultural/variety-types');
        console.log('接口返回种类:', response.data);

        this.varietyTypes = response.data.map(item => item.varietyType);
      } catch (error) {
        console.error('获取种类失败:', error);
        this.$message.error('无法加载种类，请检查网络或稍后再试');
      }
    },
    async getWarehouseLocations() {
      try {
        const response = await axios.get('/warehouse/locations');
        this.warehouseLocations = response.data.data || [];

        if (this.warehouseLocations.length > 0) {
          this.selectedLocation = this.warehouseLocations[0]; // 默认选第一个地址
        }
      } catch (error) {
        console.error('获取仓库地址失败:', error);
        this.$message.error('获取仓库地址失败，请稍后再试');
      }
    }
  }
};
</script>